package com.lanproperiesinternal.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 定时清空临时缓存文件夹
 */
@Component
@EnableScheduling
public class DeleteExpiredFile {

    @Value("${file.tmp.path}")
    private String ROOT_DIR_HISTORY_PATH;

    /**  每天4点删除 */
    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteExpiredFileTask() {
        File file = new File(ROOT_DIR_HISTORY_PATH);
        deleteExpiredFile(file);
    }

    private void deleteExpiredFile(File file) {
        if (!file.exists()) return;
        if (!file.isDirectory()) {
            determineExpiredFile(file);
        } else {
            for (File f : file.listFiles()) {
                deleteExpiredFile(f);
            }
        }
    }

    private void determineExpiredFile(File file) {
        long lastModifiedTime = file.lastModified();
        long currentTime = System.currentTimeMillis();
        // 删除上一天的临时文件
        long timeInterval = 24 * 60 * 60 * 1000;
        if (currentTime - lastModifiedTime > timeInterval) {
            file.delete();
        }
    }

}
